const Role = require('../models/role')
const setOutputModel = require('../tools/setOutput')
const setOutput = setOutputModel.setOutput

class RoleController {
  prefix = ''
  getPath(name){
    return name ? `/${this.prefix}/${name}` : `/${this.prefix}`
  }

  async add(ctx, next){ 
    ctx.verifyParams({
      roleName: { type: "string", required: true },
      roleId: { type: "string", required: true }
    })
    let obj = {...ctx.request.body, _id: ctx.request.body.roleId, accessIds: []} 
    
    const [addErr, target] = await to( new Role(obj).save() )
    if(addErr) return ctx.throw(500, addErr) 
    // const [err, data] = await to(Role.findById(target._id).lean())
    // if(addErr) return ctx.throw(500, err)
    ctx.response.body = setOutput(target.toJSON())
  }

  async find(ctx, next) {  
    const {page = 1, pageSize = 20, roleName} = ctx.request.query
    const roleNameReg = new RegExp(roleName, 'i')
    
    const total = await Role.count({  
      roleName: roleNameReg
    })

    const list = await Role.find({ 
      roleName: roleNameReg 
    }) 
    .skip((parseInt(page) - 1) * parseInt(pageSize))
    .limit(parseInt(pageSize) || 5).lean() 
    console.log('list', list)
    const data = {
      list: list,
      total: total
    }
    ctx.response.body = setOutput(data, 'fetch')
  }

  async findOne(ctx, next) {
    const [err, data] = await to(Role.findById(ctx.params.id).lean()) 
    if(err || !data) return ctx.throw(500, err) 
    ctx.response.body = setOutput(data, 'get')
  }

  async deleteMany(ctx, next) {
    const [err, data] = await to( Role.deleteMany() )
    if(err) return ctx.throw(500, err)
    ctx.response.body = {
      data: data,
      code: 0,
      msg: '成功'
    } 
  }
}

module.exports = new RoleController()